package org.zmhhxl.sample3.oauth2.a.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.zmhhxl.api.auth.RemoteThirdPartyService;
import org.zmhhxl.api.auth.domain.entity.ThirdPartyUser;
import org.zmhhxl.sample3.oauth2.a.authentications.model.CustomOAuth2User;
import org.zmhhxl.sample3.oauth2.a.service.IOauth2ThirdAccountService;

import java.util.Optional;

/**
 * <p>
 * 三方登录账户信息表 服务实现类
 * </p>
 *
 * @author vains zmhhxl
 * @since 2024-11-13
 */
@Service
@RequiredArgsConstructor
public class Oauth2ThirdAccountServiceImpl implements IOauth2ThirdAccountService {

   private final RemoteThirdPartyService remoteThirdPartyService;


   /**
    * 检查是否存在该用户信息，不存在则保存，暂时不做关联基础用户信息，由前端引导完善/关联基础用户信息
    *
    * @param basicOauth2User 用户信息
    */
   @Override
   public Optional<ThirdPartyUser> checkAndSaveUser(CustomOAuth2User basicOauth2User) {
      //先转换为第三方用户
      ThirdPartyUser thirdPartyUser = new ThirdPartyUser();
      thirdPartyUser.setThirdPartyId(basicOauth2User.getUniqueId());
      //thirdPartyUser.setThirdUsername(basicOauth2User.getThirdUsername()); //第一次时自定义
      thirdPartyUser.setCredentials(basicOauth2User.getCredentials());
      thirdPartyUser.setCredentialsExpiresAt(basicOauth2User.getCredentialsExpiresAt());
      thirdPartyUser.setThirdPartyType(basicOauth2User.getType());  // registrationId
      if(StringUtil.isNotBlank(basicOauth2User.getDomain()))
        thirdPartyUser.setThirdPartyDomain(basicOauth2User.getDomain());
      if (StringUtil.isNotBlank(basicOauth2User.getProtocol()))
        thirdPartyUser.setThirdPartyProtocol(basicOauth2User.getProtocol());

      return remoteThirdPartyService.save(thirdPartyUser).getData();
      //return null;
   }

   @Override public Optional<ThirdPartyUser> findByThirdPartyIdAndThirdPartyDomain(String id, String domain) {
      return remoteThirdPartyService.findByThirdPartyIdAndThirdPartyDomain(id,domain).getData();
   }

   @Override public Optional<ThirdPartyUser> findById(Long id) {
      return remoteThirdPartyService.findById(id).getData();
   }

   @Override public Optional<Long> findUserIdById(Long id) {
      return remoteThirdPartyService.findUserIdById(id).getData();
   }

}
